﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web;
using Hanhud.Security;
using System.Web.UI.HtmlControls;

namespace Hanhud.Web.UI
{
    /// <summary>
    /// Định nghĩa 1 trang trong module
    /// Mỗi trang sẽ có 1 tập quyền, tập quyền này được setup lúc code
    /// </summary>
    public class SitePage : UserControl, ISitePage
    {
        private string _name;
        /// <summary>
        /// The name of page
        /// </summary>
        public string Name
        {
            get { return _name; }
            protected set { _name = value; }
        }

        private string _module;
        public string Module
        {
            get { return _module; }
            private set
            {
                _module = value;
            }
        }

        private string _keywords = null;
        public string Keywords
        {
            get { return _keywords; }
            set { _keywords = value; }
        }

        private string _description;
        public string Description
        {
            get { return _description; }
            set { _description = value; }
        }

        private HANHUDHeader _header = null;
        public HANHUDHeader Header
        {
            get { return _header; }
            set { _header = value; }
        }

        private HANHUDFooter _footer = null;
        public HANHUDFooter Footer
        {
            get { return _footer; }
            set { _footer = value; }
        }

        private HANHUDNavigator _navigator = null;
        public HANHUDNavigator Navigator
        {
            get { return _navigator; }
            set { _navigator = value; }
        }

        /// <summary>
        /// Mặc định quyền hạn ở mỗi trang đều có quyền Select(View)
        /// </summary>
        private CPermission _permission = new CPermission();
        public CPermission Permission
        {
            get
            {
                return _permission;
            }
        }

        /// <summary>
        /// Mặc định là user không có quyền hạn gì ở trang
        /// </summary>
        private CPermission _userPermission = new CPermission(0);
        /// <summary>
        /// Quyền hạn của User tại mỗi trang
        /// </summary>
        public CPermission UserPermission
        {
            get { return _userPermission; }
        }

        private Masters.HANHUDMaster _master;
        public Masters.HANHUDMaster Master
        {
            get { return _master; }
            internal set { _master = value; }
        }

        public CPageContext PageContext
        {
            get { return CPageContext.Current; }
        }

        public CMembershipUser CurrentUser
        {

            get { 
#if TEST_MODE
                return new CMembershipUser();
#else
                return CPageContext.Current.User; 
#endif
            }
        }

        public SitePage()
            : this("Home", "Default")
        {
            this.Init += new EventHandler(SitePage_Init);
            this.PreRender += new EventHandler(SitePage_PreRender);
        }

        void SitePage_Init(object sender, EventArgs e)
        {
            // Lấy thông tin quyền hạn của user tại mỗi trang lúc init
            GetUserPermission();
        }

        void SitePage_PreRender(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_keywords))
            {
                // Lay danh sach cac danh muc san pham
                //List<ICategory<int, CProductCategory>> categories = Hanhud.Web.Store.CProductCategory.GetCategoryTree(-1);
                //System.Text.StringBuilder sb = new System.Text.StringBuilder();

                //foreach (ICategory<int, CProductCategory> category in categories)
                //{
                //    sb.Append(category.Title).Append(",");
                //}

                //if (sb.Length > 1) sb.Remove(sb.Length - 1, 1);

                //this.Keywords = sb.ToString();
            }

            if (string.IsNullOrEmpty(_description)) _description = string.Empty;

            HtmlMeta keywordTag = new HtmlMeta();
            keywordTag.Name = "keywords";
            keywordTag.Content = this.Keywords;
            HtmlMeta descriptionTag = new HtmlMeta();
            descriptionTag.Name = "descriptions";
            descriptionTag.Content = this.Description;

            Page.Header.Controls.AddAt(0, descriptionTag);
            Page.Header.Controls.AddAt(0, keywordTag);
        }

        private void GetUserPermission()
        {
            if (CurrentUser != null)
            {
                // Lay quen cua nguoi dung tren trang nay
                UserPermission.BitValue = CWeb.GetUserPermission(this).BitValue;
            }
        }

        public SitePage(string module, string name)
        {
            this.Module = module.ToUpper();
            this.Name = name.ToUpper();

            // Dua trang nay vao danh sach trang da duoc load
            this.Init += new EventHandler(SitePage_Init);
            this.PreRender += new EventHandler(SitePage_PreRender);
        }

        public SitePage(string module, string name, CPermission permission)
            : this(module, name)
        {
            // Gán quyền cho trang
            _permission.BitValue = _permission.BitValue | permission.BitValue;
        }

        protected override void OnLoad(EventArgs e)
        {
            // Valid request
            CheckRequestValidity(this.Request);

            base.OnLoad(e);
        }

        private static void CheckRequestValidity(HttpRequest request)
        {
            // ip with 
            // deny access if POST request comes from other server
            if (request.HttpMethod == "POST" && request.UrlReferrer != null && request.Url.Host != null && request.UrlReferrer.Host != request.Url.Host)
            {
                Hanhud.Web.CLinkBuilder.AccessDenied();
            }
        }

        public string GetImageUrl(string imageUrl)
        {
            return GetImageUrl(imageUrl, false);
        }

        public string GetImageUrl(string imageUrl, bool useTheme)
        {
            if (useTheme)
            {
                if (imageUrl.IndexOf("~/") >= 0) imageUrl = imageUrl.Replace("~/", "");
                else if (imageUrl[0] == '/') imageUrl = imageUrl.Remove(0);

                return Page.ResolveUrl(string.Format("~/App_Themes/{0}/{1}", Page.Theme, imageUrl));
            }
            else
                return Page.ResolveUrl(imageUrl);
        }

        public string GetPageUrl(string pageUrl)
        {
            string strBaseUrl = string.Empty; // CUrlBuilder.Path;

            if (pageUrl.IndexOf("~/") >= 0) pageUrl = pageUrl.Replace("~/", "");
            else if (pageUrl[0] == '/') pageUrl = pageUrl.Remove(0);

            //return string.Format("http://localhost{0}{1}", strBaseUrl, pageUrl);
            return string.Format("http://{2}{0}/{1}", Request.ApplicationPath, pageUrl, Request.Url.Host);
        }

        protected void RegisterCss(string href)
        {
            System.Web.UI.HtmlControls.HtmlLink gridCss = new System.Web.UI.HtmlControls.HtmlLink();
            gridCss.Attributes["type"] = "text/css";
            gridCss.Attributes["rel"] = "Stylesheet";

            if (href.IndexOf("~/") >= 0) href = href.Replace("~/", "");
            else if (href[0] == '/') href = href.Remove(0);

            gridCss.Href = string.Format("~/App_Themes/{0}/{1}", Config.CSiteConfig.Current.Theme, href);
            Page.Header.Controls.Add(gridCss);
        }

        protected void RegisterCss(string href, bool useTheme)
        {
            if (useTheme) RegisterCss(href);
            else
            {
                System.Web.UI.HtmlControls.HtmlLink gridCss = new System.Web.UI.HtmlControls.HtmlLink();
                gridCss.Attributes["type"] = "text/css";
                gridCss.Attributes["rel"] = "Stylesheet";

                if (href.IndexOf("~/") >= 0) href = href.Replace("~/", "");
                else if (href[0] == '/') href = href.Remove(0);

                gridCss.Href = string.Format("~/{0}", href);
                Page.Header.Controls.Add(gridCss);
            }
        }
    }
}
